package easymall.controller.admin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import easymall.clients.OrderService;
import easymall.clients.ProductsService;
import easymall.clients.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import easymall.po.Order;
import easymall.po.OrderItem;
import easymall.po.Products;
import easymall.po.User;
import easymall.pojo.OrderInfo;
import easymall.pojo.OrderRow;

@Slf4j
@Controller("orderControllerAdmin")
public class OrderControllerAdmin extends AdminFilterController{
	@Autowired
	private OrderService orderService;
	@Autowired
	private ProductsService productsService;
	@Autowired
	private UserService userService;

	// 显示订单列表
	@RequestMapping("/admin/orderlist")
	public String showOrderList(Integer page, Model model) {
		int totalPage = orderService.totalPage(); // 获取总页数
		if (page == null || page < 1)
			page = 1;
		if (page > totalPage)
			page = totalPage;

		List<OrderRow> orders = findOrderRowByPage(page);
		model.addAttribute("totalPage", totalPage);
		model.addAttribute("page", page);
		model.addAttribute("orders", orders);
		return "admin/order_list";
	}

	// 显示订单详情
	@RequestMapping("/admin/orderdetail")
	public String showOrderDetail(String id, String username, Model model) {
		OrderInfo orderInfo = findOrderByOrderId(id);
		model.addAttribute("orderInfo", orderInfo);
		model.addAttribute("username", username);
		
		return "admin/order_detail";
	}
	
	//发货
	@RequestMapping("/admin/confirmorder")
	@ResponseBody
	public String sendOrder(String id,String expressnumber) {
		orderService.sendOrder(new Order(id,expressnumber));
		return "1";
	}
	

	private OrderInfo findOrderByOrderId(String id) {
		Order order = orderService.getOrderById(id);
		List<OrderItem> orderItems = orderService.getOrderItemsByOrderId(order.getId());
		Map<Products, Integer> map = new HashMap<Products, Integer>();
		for (OrderItem orderItem : orderItems) {
			Products product = productsService.oneProduct(orderItem.getProduct_id());
			map.put(product, orderItem.getBuynum());
		}
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setOrder(order);
		orderInfo.setMap(map);
		return orderInfo;
	}

	// 根据页号查找订单信息
	private List<OrderRow> findOrderRowByPage(Integer page) {
		List<OrderRow> orderRows = new ArrayList<OrderRow>();
		List<Order> orders = orderService.getOrdersByPage(page);
		for (Order order : orders) {
			User user = userService.getUser(order.getUser_id());
			orderRows.add(new OrderRow(order, user));
		}

		return orderRows;
	}
}
